<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center;margin-bottom: 20px;"
    >
      <div>
        <div>
          模板名称:
          <el-input
            v-model="requestBody.name"
            placeholder=""
            size="small"
            style="margin-right: 10px;width: 200px;"
          />
          公司id：
          <el-input
            v-model="requestBody.gsid"
            placeholder=""
            size="small"
            style="margin-right: 10px;width: 200px;"
          />
          模板类型:
          <el-select
            v-model="requestBody.informType"
            placeholder="请选择"
            size="small"
            style="margin-right: 10px"
          >
            <el-option value="" label="全部"></el-option>
            <el-option
              v-for="item in informType"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          状态:
          <el-select
            v-model="requestBody.status"
            placeholder="请选择"
            size="small"
            style="margin-right: 15px"
          >
            <el-option value="" label="全部"></el-option>
            <el-option value="1" label="开启"></el-option>
            <el-option value="0" label="禁用"></el-option>
          </el-select>
        </div>
        <div style="margin-top: 15px">
          分类：
          <el-select
            filterable
            clearable
            v-model="form.category"
            size="small"
            placeholder="请选择分类"
            style="margin-right: 20px"
            @change="getScene(form.category)"
          >
            <el-option
              v-for="(item, i) in categoryList"
              :label="item"
              :value="item"
              :key="i"
            ></el-option>
          </el-select>
          应用场景：
          <el-select size="small" clearable filterable v-model="form.scene" style="margin-right: 20px"
                     placeholder="请选择场景">
            <el-option
              v-for="(item, i) in sceneList"
              :label="item.value"
              :value="item.value"
              :key="i"
            ></el-option>
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            size="medium"
            @click="getData"
            style="text-align:center;margin-left: 20px"
            v-permission="'talkTemplate.list'"
          >
            查询
          </el-button>
          <el-button
            class="filter-item"
            style="margin-left: 20px"
            type="primary"
            size="medium"
            @click="handleCreateNew"
            v-permission="'talkTemplate.add'"
          >
            创建话术模板
          </el-button>
        </div>
      </div>
      <div style="margin-left: auto;">
        显示条目:
        <el-select
          v-model="selectedShowTable"
          multiple
          collapse-tags
          placeholder="请选择"
          @change="handleShowTable"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
    </div>
    <el-table
      :data="data"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        prop="templateVO.name"
        label="名称"
        width="200"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.answerType"
        prop="templateVO.answerType"
        label="跳转条件"
        align="center"
      >
        <template v-slot="scope">
          {{
            scope.row.templateVO.answerType
              ? scope.row.templateVO.answerType.toString()
              : "开场白"
          }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.category"
        prop="templateVO.category"
        label="模板分类"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.scene"
        prop="templateVO.scene"
        label="应用场景"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.informType"
        prop="templateVO.informType"
        label="模板类型"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.language"
        prop="templateVO.language"
        label="语音通知"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.content"
        prop="templateVO.content"
        label="内容"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.variables"
        prop="templateVO.variables"
        label="变量"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.recorder"
        prop="templateVO.recorder"
        label="录音员"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="templateVO.gsid"
        label="所属公司id"
        align="center"
        width="50"
      ></el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.status"
        prop="templateVO.status"
        label="当前状态"
        align="center"
        width="100"
      >
        <template v-slot="scope">
          <span v-if="scope.row.templateVO.status == 1" style="color: #20a0ff">
            开启
          </span>
          <span v-if="scope.row.templateVO.status == 0" style="color: red">
            禁用
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="selectedShowTableMap.operation"
        label="操作"
        align="center"
        width="250"
      >
        <template v-slot="scope">
          <el-button
            style="margin-left: 10px"
            type="danger"
            size="mini"
            @click="deleteTemplate(scope.row.id, scope.row.templateVO.type)"
            v-permission="'talkTemplate.delete'"
          >
            删除
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleCreate(scope.row.templateVO)"
            v-permission="'talkTemplate.add'"
          >
            新增
          </el-button>
          <el-button
            type="warning"
            size="mini"
            @click="updateTemplate(scope.row.templateVO)"
            v-permission="'talkTemplate.update'"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div v-if="roles != 'user'" style="display: flex;align-items: center;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="selectedAll"
          @change="handleSelectAll"
        >
          当页全选
        </el-checkbox>
        <el-button
          style="margin-left: 10px"
          type="danger"
          @click="updateStatusFALSE"
          v-permission="'talkTemplate.forbid'"
        >
          禁用
        </el-button>
        <el-button type="primary" @click="updateStatusTRUE" v-permission="'talkTemplate.publish'">
          开启
        </el-button>
      </div>
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="requestBody.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="requestBody.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next"
      />
    </div>

    <!--创建新话术弹出框-->
    <el-dialog
      :title="textMap[dialogStatus]"
      v-model="dialogFormVisible"
      :before-close="onCancel"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="140px">
        <el-form-item label="模板类型" prop="informType">
          <el-radio-group v-model="form.informType">
            <el-radio v-for="(item, i) in informType" :label="item" :key="i" />
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus == 'createNew'"
          label="模板名称"
          prop="name"
        >
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="话术类型" prop="type">
          <el-select
            v-if="dialogStatus == 'createNew'"
            v-model="form.type"
            placeholder="开场白"
            disabled
          ></el-select>
          <el-select v-else v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="type in templateTypes"
              :disabled="type == '开场白'"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类场景">
          <el-select
            filterable
            v-model="form.category"
            placeholder="请选择分类"
            @change="getScene(form.category)"
          >
            <el-option
              v-for="(item, i) in categoryList"
              :label="item"
              :value="item"
              :key="i"
            ></el-option>
          </el-select>
          <el-select filterable v-model="form.scene" placeholder="请选择场景">
            <el-option
              v-for="(item, i) in sceneList"
              :label="item.value"
              :value="item.value"
              :key="i"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="话术语音" prop="language">
          <el-radio-group v-model="form.language">
            <el-radio label="全合成" />
            <el-radio label="全录音" />
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="this.form.language === '全合成'" label="录音员" prop="recorder">
          <el-select v-model="form.recorder" placeholder="请选择录音员">
            <el-option
              v-for="(item, i) in recorderList"
              :label="item.name"
              :value="item.name"
              :key="i"
            ></el-option>
          </el-select>
          <el-button type="primary" style="margin-left:10px;margin-right: 10px" @click="startPlayOrPause">
            {{ audioButton }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="this.form.language === '全录音'" label=" " prop="audioPath">
          <el-button type="primary" style="margin-left:10px;margin-right: 10px" @click="startPlayOrPause">
            {{ audioButton }}
          </el-button>
          <el-upload
            class="upload-audio"
            action=""
            :http-request="uploadAudio"
            :on-success="uploadAudioSuccess"
            :show-file-list="false"
            :accept="'.wav'"
          >
            <el-button prop="audioPath" v-if="form.language === '全录音'" type="primary">上传音频</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="语速" style="display: flex; flex-direction: row; align-items: center">
          <el-slider
            v-model="speedValue50"
            :format-tooltip="formatTooltip"
            style="width: 75%;margin-right: 10px"
            :min="12.5"
          ></el-slider>
          <el-input-number
            v-model="audio.speed"
            @change="handleChangeSpeed"
            :min="0.25"
            :max="2"
            label=""
            :step="0.25"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <audio ref="audio" :src="audioUrl"></audio>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus != 'createNew'"
          label="跳转类型"
          prop="answerType"
        >
          <el-select
            v-model="form.answerType"
            multiple
            placeholder="请选择话术跳转类型"
          >
            <el-option
              v-for="type in answerTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus != 'createNew'"
          label="逻辑顺序名"
          prop="logicName"
        >
          <el-input v-model="form.logicName" />
        </el-form-item>
        <el-form-item label="参数标准">
          <el-transfer
            v-model="variablesArr"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="输入参数名搜索"
            :titles="['可选参数', '已选参数']"
            :data="variables"
            @change="variableChange"
          ></el-transfer>
        </el-form-item>
        <el-form-item label="话术内容" prop="content">
          <el-input
            v-if="dialogStatus === 'createNew'"
            v-model="form.content"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="请输入开场白内容"
          />
          <el-input
            v-else
            v-model="form.content"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>

        <!--        高级配置-->
        <el-collapse style="margin-left: 65px;margin-bottom: 20px" v-model="isShowHighConfig">
          <el-collapse-item title="高级配置">
            <el-form-item label="通话开始停顿时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                style="width:85%"
                v-model="highConfig.beginTime"
                :format-tooltip="formatBeginTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.beginTime / 20 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="通话开始时,停顿设置的时间后,AI开始说话"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="挂机等待时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                v-model="highConfig.waitTime"
                style="width:85%"
                :format-tooltip="formatWaitTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.waitTime / 20 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="AI发起挂机后等待设定的时间后才挂断电话"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="用户不回复等待时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                v-model="highConfig.noResponseTime"
                style="width:85%"
                :format-tooltip="formatNoResponseTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.noResponseTime / 10 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="通话过程中,如用户不回复,等待设定的时间后触发"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="降噪等级">
              <el-select v-model="form.jzdj" placeholder="请选择">
                <el-option
                  v-for="(item, i) in jzdjList"
                  :label="item"
                  :value="item"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="识别模式">
              <el-select v-model="form.sbms" placeholder="请选择">
                <el-option
                  v-for="(item, i) in sbmsList"
                  :label="item"
                  :value="item"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">创建</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--修改updata的弹出层-->
    <el-dialog title="修改话术" v-model="dialogUpdateFormVisible" :before-close="onCancel">
      <el-form ref="updateForm" :rules="updateFormRules" :model="form" label-width="120px">
        <el-form-item label="模板类型" prop="informType">
          <el-radio-group v-model="form.informType">
            <el-radio v-for="(item, i) in informType" :label="item" :key="i" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="话术类型" prop="type">
          <el-select
            v-if="isStartTemplate"
            v-model="form.type"
            placeholder="开场白"
            disabled
          ></el-select>
          <el-select v-else v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="type in templateTypes"
              :disabled="type == '开场白'"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类场景">
          <el-select
            filterable
            v-model="form.category"
            placeholder="请选择分类"
            @change="getScene(form.category)"
          >
            <el-option
              v-for="(item, i) in categoryList"
              :label="item"
              :value="item"
              :key="i"
            ></el-option>
          </el-select>
          <el-select filterable v-model="form.scene" placeholder="请选择场景">
            <el-option
              v-for="(item, i) in sceneList"
              :label="item.value"
              :value="item.value"
              :key="i"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="话术语音" prop="language">
          <el-radio-group v-model="form.language">
            <el-radio label="全合成" />
            <el-radio label="全录音" />
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.language === '全合成'" label="录音员" prop="recorder">
          <el-select v-model="form.recorder" placeholder="请选择录音员">
            <el-option
              v-for="(item, i) in recorderList"
              :label="item.name"
              :value="item.name"
              :key="i"
            ></el-option>
          </el-select>
          <el-button style="margin-left:10px;margin-right: 10px" type="primary" @click="startPlayOrPause">
            {{ audioButton }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="form.language === '全录音'" label=" " prop="audioPath">
          <el-button style="margin-left:10px;margin-right: 10px" type="primary" @click="startPlayOrPause">
            {{ audioButton }}
          </el-button>
          <el-upload
            class="upload-audio"
            action=""
            :http-request="uploadAudio"
            :on-success="uploadAudioSuccess"
            :show-file-list="false"
            :accept="'.wav'"
          >
            <el-button prop="audioPath" v-if="form.language === '全录音'" type="primary">上传音频</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="语速" style="display: flex; flex-direction: row; align-items: center">
          <el-slider
            v-model="speedValue50"
            :format-tooltip="formatTooltip"
            style="width: 80%;margin-right: 10px"
          ></el-slider>
          <el-input-number
            v-model="audio.speed"
            @change="handleChangeSpeed"
            :min="0.02"
            :max="2"
            label=""
            :step="0.25"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <audio ref="audio" :src="audioUrl"></audio>
        </el-form-item>
        <el-form-item
          v-if="!isStartTemplate"
          label="跳转类型"
          prop="answerType"
        >
          <el-select
            v-model="form.answerType"
            multiple
            placeholder="请选择话术跳转类型"
          >
            <el-option
              v-for="type in answerTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!isStartTemplate && false"
          label="逻辑顺序名"
          prop="logicName"
        >
          <el-input v-model="form.logicName" />
        </el-form-item>
        <el-form-item label="参数标准">
          <el-transfer
            v-model="variablesArr"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="输入参数名搜索"
            :titles="['可选参数', '已选参数']"
            :data="variables"
            @change="variableChange"
          ></el-transfer>
        </el-form-item>
        <el-form-item label="话术内容" prop="content">
          <el-input
            v-model="form.content"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>

        <!-- 高级配置区域 -->
        <el-collapse style="margin-left: 65px;margin-bottom: 20px" v-model="isShowHighConfig">
          <el-collapse-item title="高级配置">
            <el-form-item label="通话开始停顿时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                v-model="highConfig.beginTime"
                style="width:85%"
                :format-tooltip="formatBeginTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.beginTime / 20 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="通话开始时,停顿设置的时间后,AI开始说话"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="挂机等待时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                v-model="highConfig.waitTime"
                style="width:85%"
                :format-tooltip="formatWaitTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.waitTime / 20 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="AI发起挂机后等待设定的时间后才挂断电话"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="用户不回复等待时长" style="display: flex; flex-direction: row; align-items: center;">
              <el-slider
                v-model="highConfig.noResponseTime"
                style="width:85%"
                :format-tooltip="formatNoResponseTime"
              ></el-slider>
              <span style="margin-left: 10px;margin-right: 15px">
            {{ highConfig.noResponseTime / 10 }}秒
          </span>
              <el-tooltip
                class="item"
                effect="light"
                content="通话过程中,如用户不回复,等待设定的时间后触发"
                placement="right"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="降噪等级">
              <el-select v-model="form.jzdj" placeholder="请选择">
                <el-option
                  v-for="(item, i) in jzdjList"
                  :label="item"
                  :value="item"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="识别模式">
              <el-select v-model="form.sbms" placeholder="请选择">
                <el-option
                  v-for="(item, i) in sbmsList"
                  :label="item"
                  :value="item"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>

        <el-form-item>
          <el-button type="primary" @click="handleUpdate">修改</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTemplate,
  deleteTemplateAll,
  deleteTemplateById,
  getData, updateStatusFALSE, updateStatusTRUE, updateTemplate
} from "@/api/talkTemplateBase/talkTemplate";
import waves from "@/directive/waves";
import { getCategory, getRecorderList, getScene, getSimpleList } from "@/api/talkTemplateBase/param";
import axios from "axios";
import request from "@/utils/request";

export default {
  directives: { waves },
  data() {
    return {
      // audio相关设置
      audioUrl: "",
      audio: {
        playing: false,
        speed: 1
      },
      speedValue50: 50,
      audioButton: "试听",
      audioButton1: "试听",
      // 创建表单
      messageText: "请输入开场白内容",
      templateTypes: [],
      answerTypes: [], // 从后端进行获取
      categoryList: [],
      sceneList: [],
      jzdjList: [],
      sbmsList: [],
      sceneAllList: [
        { category: "金融", value: "借贷" },
        { category: "金融", value: "理财" },
        { category: "电商", value: "直播" },
        { category: "电商", value: "短视频" }
      ],
      recorderList: [],
      informType: ["AI话术模板", "语音通知"],
      form: {
        informType: "",
        name: "",
        category: "",
        scene: "",
        language: "",
        recorder: "",
        variables: "",
        content: "",
        type: "",
        beforeId: "",
        answerType: [],
        logicName: "",
        speed: 1,
        // 高级配置
        beginTime: 0.5,
        waitTime: 3,
        noResponseTime: 5,
        jzdj: "",
        sbms: "",
        audioPath: ""
      },
      rules: {
        informType: [
          { required: true, message: "模板类型不能为空"}
        ],
        name: [
          { required: true, message: "模板名称不能为空"}
        ],
        language: [
          { required: true, message: "话术语言不能为空"}
        ],
        recorder: [
          { required: true, message: "录音员不能为空"}
        ],
        audioPath: [
          { required: true, message: "音频不能为空"}
        ],
        type: [
          { required: true, message: "请选择话术类型"}
        ],
        answerType: [
          { required: true, message: "请选择话术跳转类型"}
        ],
        content: [
          { required: true, message: "模板内容不能为空"}
        ]
      },
      updateFormRules: {
        informType: [
          { required: true, message: "模板类型不能为空"}
        ],
        name: [
          { required: true, message: "模板名称不能为空"}
        ],
        language: [
          { required: true, message: "话术语言不能为空"}
        ],
        recorder: [
          { required: true, message: "录音员不能为空"}
        ],
        audioPath: [
          { required: true, message: "音频不能为空"}
        ],
        type: [
          { required: true, message: "请选择话术类型"}
        ],
        answerType: [
          { required: true, message: "请选择话术跳转类型"}
        ],
        content: [
          { required: true, message: "模板内容不能为空"}
        ]
      },
      // 弹出层是否可见
      dialogFormVisible: false,
      // 弹出层的状态,是创建,还是修改
      dialogStatus: "create",
      // 弹出层的状态
      textMap: {
        update: "修改话术",
        createNew: "创建新话术模板",
        create: "创建话术"
      },
      // 修改相关
      dialogUpdateFormVisible: false,
      isStartTemplate: false, // 记录当前修改的话术是否是开场白 用于显示修改的表单不同
      // 参数设置
      variablesArr: [],
      // params: generateParams(),
      variables: this.getVariables(),
      // 高级配置
      isShowHighConfig: false,
      highConfig: {
        beginTime: 10,
        waitTime: 60,
        noResponseTime: 50
        // jzdj: '',
        // sbms: ''
      },
      filterMethod(query, item) {
        // return item.pinyin.indexOf(query) > -1
        return item.label.indexOf(query) > -1;
      },
      // 请求数据的请求对象
      requestBody: {
        name: "",
        gsid: "",
        scene: "",
        category: "",
        informType: "",
        status: "",
        pageNum: 1,
        pageSize: 10
      },
      // 获取到的话术模板数据
      data: [],
      heads: [],
      total: 0,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 控制是否显示
      selectedRows: [],
      selectedAll: false,
      isIndeterminate: false,
      options: [
        {
          value: "answerType",
          label: "跳转条件"
        },
        {
          value: "category",
          label: "模板分类"
        },
        {
          value: "scene",
          label: "应用场景"
        },
        {
          value: "informType",
          label: "模板类型"
        },
        {
          value: "language",
          label: "语音通知"
        },
        {
          value: "content",
          label: "内容"
        },
        {
          value: "variables",
          label: "变量"
        },
        {
          value: "recorder",
          label: "录音员"
        },
        {
          value: "status",
          label: "当前状态"
        },
        {
          value: "operation",
          label: "操作"
        }
      ],
      selectedShowTable: [
        "answerType",
        "content",
        "variables",
        "recorder",
        "status",
        "operation"
      ],
      selectedShowTableMap: {
        answerType: true,
        category: false,
        scene: false,
        informType: false,
        language: false,
        content: true,
        variables: true,
        recorder: true,
        status: true,
        operation: true
      }
    };
  },
  mounted() {
    this.getData();
    this.getAnswerType();
    this.getTemplateType();
    this.getRecorderList();
    this.getjzdjList();
    this.getsbmsList();
    this.getCategory();
  },
  methods: {
    sizeChange(size) {
      this.requestBody.pageSize = size
      this.getData()
    },
    currentChange(current) {
      this.requestBody.pageNum = current
      this.getData()
    },
    // 创建话术
    handleCreateNew() {
      this.resetForm();
      this.dialogStatus = "createNew";
      this.form.type = "开场白";
      this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["form"].clearValidate();
      // });
    },
    handleCreate(templateVO) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // 设置beforeId afterId
      this.form.beforeId = templateVO.id;
      // console.log(templateVO, 'parent templateVO')
      // 将上级的name,category,scene设置到新增话术的字段的,保证新增话术的这三个字段和父话术保持一致
      this.form.name = templateVO.name;
      this.form.category = templateVO.category;
      this.form.scene = templateVO.scene;
      // this.$nextTick(() => {
      //   this.$refs["form"].clearValidate();
      // });
    },
    // 获取数据
    getData() {
      console.log('requestBody', this.requestBody)
      console.log('num', this.pageNum)
      console.log('size', this.pageSize)
      const _requestBody = this.requestBody;
      _requestBody.category = this.form.category;
      _requestBody.scene = this.form.scene;
      getData(_requestBody).then(response => {
        // console.log(response, "话术模板数据");
        this.data = response.data.content;
        this.total = response.data.totalElements;
      });
    },
    // 获取字典
    getAnswerType() {
      getSimpleList("answerType").then(response => {
        this.answerTypes = response.data;
      });
    },
    getTemplateType() {
      getSimpleList("templateType").then(response => {
        this.templateTypes = response.data;
      });
    },
    getCategory() {
      getCategory().then(response => {
        this.categoryList = response.data
        // console.log(this.categoryList)
      });
    },
    getVariables() {
      const params = [];
      getSimpleList("variable").then(response => {
        var valNames = response.data;
        valNames.forEach((valName, index) => {
          params.push({
            label: valName,
            key: valNames[index]
          });
        });
      });
      return params;
    },
    getRecorderList() {
      getRecorderList().then(response => {
        this.recorderList = response.data
      })
    },
    getjzdjList() {
      getSimpleList("jzdj").then(response => {
        this.jzdjList = response.data;
      });
    },
    getsbmsList() {
      getSimpleList("sbms").then(response => {
        this.sbmsList = response.data;
      });
    },
    // 分类和应用场景联动选择
    getScene(category) {
      getScene(category).then(response => {
        this.sceneAllList = response.data;
        this.form.scene = "";
        this.sceneList = [];
        for (var scene of this.sceneAllList) {
          if (scene.category === category) {
            this.sceneList.push(scene);
          }
        }
      });
    },
    // 试听相关方法
    startPlayOrPause() {
      this.audio.playing ? this.pausePlay() : this.startPlay();
    },
    // 开始播放
    startPlay() {
      if (this.form.language === '') {
        this.$message.error("请先选择话术语音!");
        return
      }
      let audioPath = "";
      const recorder = this.form.recorder;
      if (this.form.language === '全合成') {
        this.recorderList.forEach(item => {
          if (item.name === recorder) {
            audioPath = item.audioPath
          }
        })
        if (audioPath === '' || audioPath === null) {
          this.$message.error("录音员未选择或该录音员未配置试听音频!");
          return
        }
      }
      if (this.form.language === '全录音') {
        if (this.form.audioPath === '') {
          this.$message.error("请先上传音频!");
          return
        } else {
          audioPath = this.form.audioPath
        }
      }
      Promise.all([this.getAudioByPath(audioPath)]).then(res => {
        if (res == -1) {
          return;
        } else {
          this.audio.playing = true;
          this.audioButton = "暂停";
          this.$refs.audio.currentTime = 0;
          this.$refs.audio.playbackRate = this.audio.speed;
          this.$refs.audio.play();
        }
      });
    },
    // 暂停
    pausePlay() {
      this.audio.playing = false;
      this.audioButton = "试听";
      // this.speedValue50 = 50
      this.$refs.audio.pause();
    },
    formatTooltip(val) {
      if (val == null) {
        val = 50;
      }
      if (val <= 4) {
        val = 4;
      }
      // console.log(val, 'val')
      const speed = val / 50;
      this.audio.speed = speed;
      if (this.$refs.audio !== undefined) {
        this.$refs.audio.playbackRate = speed;
      }
      return speed;
    },
    formatBeginTime(val) {
      return val / 20;
    },
    formatWaitTime(val) {
      return val / 20;
    },
    formatNoResponseTime(val) {
      return val / 10;
    },
    handleChangeSpeed(speed) {
      this.speedValue50 = speed * 50;
      this.$refs.audio.playbackRate = speed;
    },
    async getAudioByPath(audioPath) {
      try {
        const response = await axios({
          url: audioPath,
          method: "GET",
          responseType: "blob"
        });
        if (response.data.type === "application/json") {
          // console.log('获取音频失败!')
          this.$message.error("获取音频失败!");
          return -1;
        }
        const audioBlob = new Blob([response.data], { type: "audio/mpeg" });
        this.audioUrl = URL.createObjectURL(audioBlob);
      } catch (error) {
        // console.log('获取音频失败!')
        this.$message.error("获取音频失败!");
        return -1;
      }
    },
    uploadAudio(options){
      const formData = new FormData;
      formData.append('file',options.file);
      request.post('/audio/uploadAudio', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then(res => {
        options.onSuccess(res, options.file)
      }).catch(error => {
        this.$message.error("上传音频失败!");
      })
    },
    uploadAudioSuccess(resp) {
      this.form.audioPath = resp.data
      this.$message.success("上传成功!")
      if (this.$refs.form) {
        this.$refs.form.validateField('audioPath')
      }
      if (this.$refs.updateForm) {
        this.$refs.updateForm.validateField('audioPath')
      }
    },
    handleUpdate() {
      // console.log(this.variablesArr, 'variablesArr')
      // TO DO 不知道为什么,variablesArr数组首位元素为空,导致拼接出来的字符串为,开头
      // 去除首位元素
      if (this.variablesArr[0] === "") {
        this.variablesArr.shift()
      }
      this.form.variables = this.variablesArr.toString()
      this.form.speed = this.audio.speed;
      this.form.beginTime = this.highConfig.beginTime / 20
      this.form.waitTime = this.highConfig.waitTime / 20
      this.form.noResponseTime = this.highConfig.noResponseTime / 10
      console.log(this.form, "form");
      this.$refs.updateForm.validate(valid => {
        if (valid) {
          // 发送表单数据
          updateTemplate(this.form).then(response => {
            this.dialogUpdateFormVisible = false;
            this.$message.success("修改成功!");
            this.resetForm();
            this.getData();
          });
          this.$nextTick(() => {
            this.$refs["form"].clearValidate();
          });
        }
      });
    },
    // 重置表单
    resetForm() {
      this.form = {
        informType: "",
        name: "",
        category: "",
        scene: "",
        language: "全合成",
        recorder: "",
        audioPath: "",
        variables: "",
        content: "",
        type: "",
        beforeId: "",
        answerType: [],
        logicName: "",
        jzdj: "正常",
        sbms: "通用模式"
      };
      this.isShowHighConfig = false
      // this.categoryList = [];
      // this.sceneList = [];
      this.variablesArr = [];
      this.highConfig = {
        beginTime: 10,
        waitTime: 60,
        noResponseTime: 50
      };
      this.$nextTick(() => {
        if(this.$refs.form !== undefined) {
          this.$refs.form.clearValidate();
        }
        if (this.$refs.updateForm !== undefined) {
          this.$refs.updateForm.clearValidate();
        }
      })
    },
    // 提交表单数据
    onSubmit() {
      this.form.variables = this.variablesArr.toString();
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.speed = this.audio.speed;
          this.form.beginTime = this.highConfig.beginTime / 20;
          this.form.waitTime = this.highConfig.waitTime / 20;
          this.form.noResponseTime = this.highConfig.noResponseTime / 10;
          console.log(this.form);
          // 发送表单数据
          addTemplate(this.form).then(response => {
            this.dialogFormVisible = false;
            this.$message.success("创建成功!");
            this.resetForm()
            this.getData();
          });
          this.$nextTick(() => {
            if(this.$refs.form !== undefined) {
              this.$refs.form.clearValidate();
            }
            if(this.$refs.updateForm !== undefined) {
              this.$refs.updateForm.clearValidate();
            }
          });
        }
      });
    },
    // 取消表单
    onCancel() {
      this.pausePlay();
      this.resetForm();
      this.dialogFormVisible = false;
      this.dialogUpdateFormVisible = false;
      this.$nextTick(() => {
        if(this.$refs.form !== undefined) {
          this.$refs.form.clearValidate();
        }
      });
    },
    updateTemplate(templateVO) {
      // 判断该话术是否是开场白
      console.log('templateVO', templateVO)
      // if (templateVO.parentId === null) {
      if (templateVO.type === '开场白') {
        this.form.type = "开场白";
        this.isStartTemplate = true;
      } else {
        // 设置非开场白的属性
        this.form.type = templateVO.type;
        this.form.answerType = templateVO.answerType;
        this.form.logicName = templateVO.logicName;
        this.isStartTemplate = false;
      }
      console.log('isStartTemplate', this.isStartTemplate)
      // this.form = templateVO
      // 共有属性,即开场白和其他话术都有的
      this.form.id = templateVO.id;
      this.form.informType = templateVO.informType;
      this.form.language = templateVO.language;
      this.form.recorder = templateVO.recorder;
      this.form.content = templateVO.content;
      this.variablesArr = templateVO.variables.split(",");
      // 设置名称,分类,应用场景
      this.form.name = templateVO.name;
      this.form.category = templateVO.category;
      this.form.scene = templateVO.scene;
      this.form.audioPath = templateVO.audioPath;
      // 设置高级配置
      this.audio.speed = templateVO.speed;
      this.highConfig.beginTime = templateVO.beginTime * 20;
      this.highConfig.waitTime = templateVO.waitTime * 20;
      this.highConfig.noResponseTime = templateVO.noResponseTime * 10;
      this.speedValue50 = templateVO.speed * 50;
      this.form.jzdj = templateVO.jzdj;
      this.form.sbms = templateVO.sbms;
      this.dialogUpdateFormVisible = true;
    },
    // 参数选择变化函数
    variableChange(value, direction, arr) {
      if (direction === "right") {
        for (let i = 0; i < arr.length; i++) {
          this.form.content += "{{" + arr[i] + "}}";
        }
      }
      if (direction === "left") {
        for (let i = 0; i < arr.length; i++) {
          this.form.content = this.form.content.replaceAll(
            "{{" + arr[i] + "}}",
            ""
          );
        }
      }
    },
    // 删除某个话术或整个话术模板
    deleteTemplate(id, type) {
      var mesg = "";
      if (type == '开场白') {
        mesg = "是否删除整个模板?";
      } else {
        mesg = "是否删除该数据?";
      }
      this.$confirm(mesg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 用户点击了确定按钮，执行删除操作
          if (type == '开场白') {
            console.log("删除整个模板");
            deleteTemplateAll(id).then(response => {
              if (response.code === 20000) {
                this.$message.success("删除成功!");
                this.getData();
              }
            });
          } else {
            // console.log('根据id删除')
            deleteTemplateById(id).then(respose => {
              if (respose.code === 20000) {
                this.$message.success("删除成功!");
                this.getData();
              }
            });
          }
        })
        .catch(() => {
          // 用户点击了取消按钮，不执行任何操作
          this.$message.success("取消成功");
        });
    },
    updateStatusTRUE() {
      this.$confirm("是否开启所选话术模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateStatusTRUE(this.selectedRows).then(response => {
            this.$message.success("修改成功!");
            this.$refs.multipleTable.clearSelection();
            this.getData();
          });
        })
        .catch(() => {
          this.$message.info("取消操作");
        });
    },
    updateStatusFALSE() {
      this.$confirm("是否禁用所选话术模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateStatusFALSE(this.selectedRows).then(response => {
            this.$message.success("修改成功!");
            this.$refs.multipleTable.clearSelection();
            this.getData();
          });
        })
        .catch(() => {
          this.$message.info("取消操作");
        });
    },
    handleSelectionChange(selection) {
      // console.log(selection, 'selection')
      this.selectedRows = [];
      for (let i = 0; i < selection.length; i++) {
        this.selectedRows.push(selection[i].id);
      }
      // console.log(this.selectedRows, 'selectedRows')
      const isSelectedAll = this.selectedRows.length === this.data.length;
      if (isSelectedAll) {
        this.selectedAll = isSelectedAll;
        this.isIndeterminate = false;
      } else {
        this.selectedAll = isSelectedAll;
        if (this.selectedRows.length !== 0) {
          this.isIndeterminate = true;
        } else {
          this.isIndeterminate = false;
        }
      }
    },
    handleSelectAll(value) {
      this.selectedAll = value;
      this.isIndeterminate = false;
      if (value) {
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 改变查看哪些表头
    handleShowTable() {
      for (const selectedShowTableMapKey in this.selectedShowTableMap) {
        if (this.selectedShowTable.includes(selectedShowTableMapKey)) {
          this.selectedShowTableMap[selectedShowTableMapKey] = true;
        } else {
          this.selectedShowTableMap[selectedShowTableMapKey] = false;
        }
      }
    }
  },
  filters: {
    transPlayPause(value) {
      return value ? "暂停" : "试听";
    }
  }
};
</script>

<style scoped lang="scss">
// 修改图标 > 为 +
::v-deep .cell .el-icon-arrow-right:before {
  // content: "+";
  color: #1890ff;
  font-size: 20px;
  font-weight: 700;
}

::v-deep .el-table__expand-icon .el-icon-arrow-right:before {
  content: '+';
}

// el-table表格对齐
// 对齐根节点 无论有无子节点
::v-deep(.el-table__row:not([class*='el-table__row--level-'])) {
  td:first-child {
    padding-left: 24px;
  }
}

// 修改展开之后的图标
::v-deep .el-table__expand-icon--expanded .el-icon-arrow-right:before {
  content: '-';
}

::v-deep .el-table__placeholder::before {
  margin-left: 20px;
}

// 修改子元素选择框的样式
::v-deep [class*='el-table__row--level-'] .el-checkbox__inner {
  display: none;
}

::v-deep .el-table__row--level-0 .el-checkbox__inner {
  display: inline-block;
}

// 修改子节点样式
$table-levels: 13; // 定义表格层级数
//$background-colors: #AAAAAA #CCCCCC #EEEEEE #F5F5F5 #HHHHHH #IIIIII #KKKKKK; // 定义不同层级的背景颜色
$background-colors: #cdc9c9 #d1eeee #daa520 #d02090 #cdcd00 #ee3b3b #90ee90 #8e8e38 #adff2f #1c86ee #20b2aa #2f4f4f #363636; // 定义不同层级的背景颜色

@for $i from 1 through $table-levels {
  ::v-deep .el-table__row--level-#{$i} {
    background-color: nth($background-colors, $i);
  }
}

</style>
